<template>
  <el-card class="w-full pt-[5px] pb0">
    <CheckType
      v-model="searchForm.checkstatusByGroup"
      @typeChange="handleSearch"
      :countMap="countMap"
    />
    <el-form :model="searchForm" class="mt-[20px]" label-width="96px" ref="searchFormRef">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="项目名称" prop="proName">
            <el-input v-model="searchForm.proName" placeholder="项目名称" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="负责人" prop="chargerName" >
            <el-input v-model="searchForm.chargerName" placeholder="负责人" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="项目分类" prop="projectTypeCode">
            <CustomTreeSelect
              placeholder="项目分类"
              v-model="searchForm.projectTypeCode"
              valueKey="id"
              labelKey="label"
              :dataList="projectTypeList"
              :isFetch="false"
            />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <div class="flex justify-end">
            <el-button type="primary" @click="searchFormOpen = !searchFormOpen"
              >更多
              <el-icon color="#fff">
                <CaretTop v-show="searchFormOpen" />
                <CaretBottom v-show="!searchFormOpen" />
              </el-icon>
            </el-button>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetForm">重置</el-button>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="20" v-show="searchFormOpen">
        <el-col :span="12">
          <el-form-item label="" label-width="0">
            <CommonDateSelect
              placeholder="结项日期"
              v-model:startTime="searchForm.startTime"
              v-model:endTime="searchForm.endTime"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="所属单位" prop="unitId">
            <CustomTreeSelect
              placeholder="所属单位"
              v-model="searchForm.unitId"
              valueKey="codeColumn"
              labelKey="valueColumn"
              :isFetch="false"
              :dataList="unitList"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="审核状态" prop="checkstatus">
            <CustomTreeSelect
              placeholder="审核状态"
              v-model="searchForm.checkstatus"
              valueKey="dictValue"
              labelKey="dictLabel"
              :isFetch="false"
              :dataList="checkStatusList"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-card>
  <el-card class="w-full pt-[5px] mt-[10px]">
    <div class="mb-[20px]">
      <el-button @click="handleExport">
        <svg-icon iconClass="export" class="mr-[5px]"></svg-icon>导出
      </el-button>
    </div>
    <el-table :data="tableData" class="w-full" stripe v-loading="loading">
      <el-table-column label="项目名称">
        <template #default="{ row }">
          <el-link type="primary" @click="handleShow(row.projectId)">{{ row.proName }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="负责人" width="90">
        <template #default="{ row }">
          <el-link
            type="primary"
            @click="handleViewPerson(row.chargerCode)"
            v-if="row.chargerCode"
            >{{ row.chargerName }}</el-link
          >
          <span v-else>{{ row.chargerName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="项目分类"  width="200">
        <template #default="{ row }">
          <CommonTreeLabel
            :value="row.projectType"
            :dataList="projectTypeList"
            labelKey="labelLocal"
          />
        </template>
      </el-table-column>
      <el-table-column prop="completeDate" label="结项日期"  width="100"/>
      <el-table-column label="审核状态" width="100">
        <template #default="{ row }">
          <CommonLabel
            :dataList="checkStatusList"
            valueKey="dictValue"
            labelKey="dictLabel"
            :value="row.checkstatus"
          />
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="200" align="center">
        <template #default="{ row }">
          <!-- 科研管理员 -->
          <template v-if="verifyRoleType.iskycgly()">
            <el-button
              type="primary"
              size="small"
              plain
              @click="handleEdit(row.id, row.projectId, row.taskId, row.isAuditor)"
              v-if="[-1, 1, 3].includes(Number(row.checkstatus))"
            >
              编辑
            </el-button>
          </template>
          <el-button
            type="success"
            size="small"
            plain
            @click="handleCheck(row.projectId, row.id, row.processInstanceId)"
            v-if="row.isAuditor"
            >审核</el-button
          >
          <el-button
            type="primary"
            size="small"
            plain
            @click="handleView(row.projectId, row.id)"
            v-if="[-1, 1, 2, 3].includes(Number(row.checkstatus))"
          >
            查看
          </el-button>
          <el-button
            type="danger"
            size="small"
            plain
            @click="handleDel(row.id)"
            v-if="[-1, 3].includes(Number(row.checkstatus))"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="mt-[20px] flex justify-end">
      <el-pagination
        v-bind="pagination"
        @update:current-page="currentChange"
        @update:page-size="sizeChange"
      />
    </div>
  </el-card>
  <EditModal ref="editModelRef" @save-success="handleSearch" />
  <CheckModal ref="checkModelRef" @check-success="handleSearch" />
  <ViewModal ref="viewModelRef" />
  <ViewProject ref="viewProjectRef" />
  <PersonView ref="personViewModalRef" />
  <exportModal
    v-model="exportVisible"
    :selectList="exportFieldList"
    :title="exportTitle"
    @callBack="handleSelectOk"
  />
</template>

<script setup>
import useTable from "@/hooks/useTable";
import CustomTreeSelect from "@/views/project/components/CustomTreeSelect.vue";
import CommonDateSelect from "@/views/project/components/CommonDateSelect.vue";
import CheckType from "@/views/project/components/CheckType.vue";
import CommonLabel from "@/views/project/components/CommonLabel.vue";
import CommonTreeLabel from "@/views/project/components/CommonTreeLabel.vue";
import EditModal from "@/views/project/components/xmjx/EditModal.vue";
import CheckModal from "@/views/project/components/xmjx/CheckModal.vue";
import ViewModal from "@/views/project/components/xmjx/ViewModal.vue";
import ViewProject from "@/views/project/components/ViewProject";
import exportModal from "@/components/export";
import PersonView from "@/views/project/components/PersonView.vue";
import { getList, delRecords, exportRecords, getCount } from "@/api/project/zx/xmjx";
import useCommonFetch from "@/hooks/useCommonFetch";
import useDictFetch from "@/hooks/useDictFetch";
import { verifyRoleType, downloadFile } from "@/utils/main";
import { exportFields } from "@/api/project/common";
import { ElMessage } from "element-plus";
const unitList = useCommonFetch("成果归属单位");
const checkStatusList = useDictFetch("bpm_process_instance_status"); //审核状态
const projectTypeList = useCommonFetch("项目分类（横向）");
const searchFormOpen = ref(false);
const searchFormRef = ref();
const editModelRef = ref();
const viewModelRef = ref();
const checkModelRef = ref();
const viewProjectRef = ref();
const personViewModalRef = ref();
const exportFieldList = ref([]);
const exportVisible = ref(false);
const exportTitle = "进账合同结项";
const countMap = ref({
  total: 0,
  1: 0,
  2: 0,
  3: 0,
});
const searchForm = ref({
  proClass: "yfContract",
  checkstatusByGroup: "",
  proName: "",
  chargerName: "",
  projectTypeCode: [],
  unitId: [],
  checkstatus: [],
  startTime: "",
  endTime: "",
});
const { loading, pagination, sizeChange, currentChange, tableData, handleDelete, search } =
  useTable(
    (pagin) =>
      getList({
        pageNo: pagin.pageNum,
        pageSize: pagin.pageSize,
        ...searchForm.value,
        projectTypeCode: searchForm.value.projectTypeCode.join(","),
        unitId: searchForm.value.unitId.join(","),
        checkstatus: searchForm.value.checkstatus.join(","),
      }),
    { getCountStatistics }
  );
getCountStatistics();
//点击项目名称
const handleShow = (id) => {
  viewProjectRef.value.view(id, "yfContract");
};
//点击查看
const handleView = (projectId, id) => {
  viewModelRef.value.view(projectId, id);
};
//点击人员姓名
const handleViewPerson = (id) => {
  personViewModalRef.value.view(id);
};
//点击编辑
const handleEdit = (id, projectId, taskId, isAuditor) => {
  editModelRef.value.edit(id, projectId, taskId, isAuditor);
};
//点击删除
const handleDel = (id) => {
  handleDelete(delRecords, id);
};
//点击审核
const handleCheck = (projectId, id, processId) => {
  checkModelRef.value.check(projectId, id, processId);
};
//获取导出字段
const getExportFileds = async () => {
  try {
    const params = {
      exportType: "complete",
      proClass: "yfContract",
    };
    const res = await exportFields(params);
    if (res.code == 200) {
      const defaultCheckedList = ["proCode", "proName", "chargerName", "proTypeName", "unitName"];
      res.data.forEach((item) => {
        exportFieldList.value.push({
          lable: item.showName,
          value: item.field,
          isSelect: defaultCheckedList.includes(item.field) ? true : false,
        });
      });
    }
  } catch (error) {
    console.log(error);
  }
};
//点击导出按钮
const handleExport = async () => {
  //exportFieldList为空时才获取数据
  if (!exportFieldList.value.length) {
    await getExportFileds();
  }
  exportVisible.value = true;
};
//导出字段选择完毕
const handleSelectOk = async (val) => {
  const cols = val.map((item) => item.prop);
  try {
    const params = {
      ...searchForm.value,
      projectTypeCode: searchForm.value.projectTypeCode.join(","),
      unitId: searchForm.value.unitId.join(","),
      checkstatus: searchForm.value.checkstatus.join(","),
      exportStr: cols.join(","),
    };
    const res = await exportRecords(params);
    if (res.type != "application/json") {
      downloadFile(res, exportTitle + ".xlsx");
    } else {
      ElMessage({
        message: "导出失败！",
        type: "error",
      });
    }
  } catch (error) {
    console.log(error);
  }
};
//获取检索数量统计
async function getCountStatistics() {
  const params = {
    ...searchForm.value,
    projectTypeCode: searchForm.value.projectTypeCode.join(","),
    unitId: searchForm.value.unitId.join(","),
    checkstatus: searchForm.value.checkstatus.join(","),
    checkstatusByGroup: "",
  };
  try {
    const res = await getCount(params);
    countMap.value = {
      total: 0,
      1: 0,
      2: 0,
      3: 0,
    };
    if (res.data) {
      let totalCount = 0;
      res.data.forEach((item) => {
        countMap.value[item.classValue] = item.classCount;
        totalCount += Number(item.classCount);
      });
      countMap.value.total = totalCount;
    }
  } catch (error) {
    console.log(error);
  }
}
//点击重置
const resetForm = () => {
  searchFormRef.value.resetFields();
  searchForm.value.startTime = "";
  searchForm.value.endTime = "";
  handleSearch();
};
//执行检索并获取数量统计
const handleSearch = () => {
  search();
  getCountStatistics();
};
</script>

<style scoped lang="scss"></style>
